package base.service.sys.impl;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import base.dao.sys.FileDao;
import base.service.sys.FileService;
import base.util.PropUtil;
import base.util.ResultMessage;

/**
 * 文件上传下载相关
 * @author JZH
 *
 */
@Service
public class FileServiceImpl implements FileService {

	@Autowired
	private FileDao fileDao;
	
	/**
	 * 文件上传
	 */
	@Override
	public ResultMessage<?> uploadFile(String description, MultipartFile file, Integer userId) {
		// TODO Auto-generated method stub
		String path = PropUtil.get("file_upload_path").toString();
        String filename = file.getOriginalFilename();//上传文件名
        File filepath = new File(path,filename);
        if (!filepath.getParentFile().exists()) { //判断路径是否存在，如果不存在就创建一个
            filepath.getParentFile().mkdirs();
        }
        try {//将上传文件保存到一个目标文件当中
			file.transferTo(new File(path + File.separator + filename));
			int result = fileDao.saveFile(filename, path, description, userId);
			if(result == 1) {
				return ResultMessage.createSuccessResultMessage("上传成功");
			}
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return ResultMessage.createErrorResultMessage("上传失败");
	}

	/**
	 * 获取所有上传的文件
	 */
	@Override
	public List<Map<String, Object>> allFiles() {
		// TODO Auto-generated method stub
		List<Map<String, Object>> maps = fileDao.allFiles();
		return maps;
	}

	/**
	 * 文件下载
	 */
	@Override
	public ResponseEntity<byte[]> downloadFile(Integer id) {
		// TODO Auto-generated method stub
		Map<String, Object> map = fileDao.getPathAndNameById(id);
		if(null != map) {
			String path = map.get("FILE_PATH").toString();
			String name = map.get("FILE_NAME").toString();
			File file = new File(path+name);
			HttpHeaders headers = new HttpHeaders();  
	        //下载显示的文件名，解决中文名称乱码问题  
	        String downloadFielName = null;
			try {
				downloadFielName = new String(name.getBytes("UTF-8"),"iso-8859-1");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        //通知浏览器以attachment（下载方式）打开图片
	        headers.setContentDispositionFormData("attachment", downloadFielName); 
	        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	        try {
				return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
				        headers, HttpStatus.CREATED);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		return null;
	}
	
	@Override
	public Map<String, Object> getPathAndNameById(Integer id) {
		return fileDao.getPathAndNameById(id);
	}
}
